//
//  HRSettingTableViewModel.m
//  Hear
//
//  Created by mac on 2017/3/28.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRSettingTableViewModel.h"
#import "HRBlackListViewController.h"
#import "HRFeedBackViewController.h"
#import "HRClearCacheTool.h"
#import "JPVideoPlayerCache.h"
#import "HRContactsManager.h"
#import "HRLocationViewModel.h"
#import "YContactObject.h"
@interface HRSettingTableViewModel ()
@property (nonatomic, strong) NSArray *dataArrayList;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)HRLocationViewModel *locationViewModel;
@property(nonatomic, assign)BOOL isIMNotifi;
@property(nonatomic, assign)BOOL isJpushNotifi;

@end
@implementation HRSettingTableViewModel
#pragma mark - Get and Set
- (HRLocationViewModel *)locationViewModel{
    if (_locationViewModel == nil) {
        _locationViewModel = [[HRLocationViewModel alloc] init];
    }
    return _locationViewModel;
}



- (NSArray *)dataArrayList {
    if (_dataArrayList == nil) {
        _dataArrayList = [NSMutableArray arrayWithObjects:@"屏蔽通讯录好友",@"关闭好友推送",@"关闭系统推送",@"清除缓存",@"黑名单",@"评价Hearer", nil];
    }
    return _dataArrayList;
}

- (void)handleWithTable:(UITableView *)table
{
    self.tableView = table;
    table.delegate = self;
    table.dataSource = self;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArrayList.count;
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellID = @"HRSettingCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
        if(indexPath.row == 0){
            UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(kFullWidth-65, 8, 40, 20)];
            mySwitch.on = [[HRContactsManager shareInstance] hasOpenContactsPower];
            [mySwitch addTarget:self action:@selector(cutPowerClick:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:mySwitch];
        }else if (indexPath.row == 1){
            UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(kFullWidth-65, 8, 40, 20)];
            mySwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"easemobSwitch"];
            [mySwitch addTarget:self action:@selector(switchImClick:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:mySwitch];
        }else if (indexPath.row == 2){
            UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(kFullWidth-65, 8, 40, 20)];
            mySwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"jpushSwitch"];
            [mySwitch addTarget:self action:@selector(switchSystemClick:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:mySwitch];
        }
        
        UILabel *lineLabel = [UILabel new];
        lineLabel.backgroundColor =CustomColor(240, 240, 240, 1);
        [cell  addSubview:lineLabel];
        
        cell.textLabel.text = self.dataArrayList[indexPath.row];
        cell.textLabel.textColor = FirstTextColor;
    }

    
    if (indexPath.row == 3){
        cell.detailTextLabel.text = [self getCaseData];
    }
    
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    WeakSelf
    if(indexPath.row == 3){
        [[YYImageCache sharedCache].diskCache removeAllObjects];
        [[YYImageCache sharedCache].memoryCache removeAllObjects];

        [[JPVideoPlayerCache sharedCache] clearDiskOnCompletion:^{
            DDLog(@"clear disk finished, 清空磁盘完成");
            
            [weakSelf calculateCacheMes];
        }];
        
        [HRClearCacheTool clearCaches];
        [self.tableView reloadData];
    }else if (indexPath.row == 4){
        HRBlackListViewController *blackVC = [HRBlackListViewController new];
        [VIEWCCONTROLER.navigationController pushViewController:blackVC animated:YES];
    }else if (indexPath.row == 5){
        NSString *str = [NSString stringWithFormat:@"http://itunes.apple.com/cn/app/id%d",1230817328];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}

- (void)switchImClick:(UISwitch *)swich{
    if (swich.isOn){
        EMPushOptions *options = [[EMClient sharedClient] pushOptions];
        options.noDisturbStatus = EMPushNoDisturbStatusDay;
        EMError *error = [[EMClient sharedClient] updatePushOptionsToServer];
        if (!error){
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"easemobSwitch"];
        }
        
    }else{
        EMPushOptions *options = [[EMClient sharedClient] pushOptions];
        options.noDisturbStatus = EMPushNoDisturbStatusClose;
        options.noDisturbingStartH = 0;
        options.noDisturbingEndH = 24;
        EMError *error = [[EMClient sharedClient] updatePushOptionsToServer];
        if (!error){
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"easemobSwitch"];
        }
    }
}

- (void)switchSystemClick:(UISwitch *)swich{
    if (swich.isOn){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"jpushSwitch"];
        [[UIApplication sharedApplication] unregisterForRemoteNotifications];
   }else{
       [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
       [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"jpushSwitch"];
    }

}


- (void)cutPowerClick:(UISwitch *)mySwitch{
    WeakSelf
    if (mySwitch.on){
        NSMutableArray *mobileNumArr = [NSMutableArray array];
        [[HRContactsManager shareInstance] requestContactsComplete:^(NSArray<YContactObject *> * _Nonnull contacts) {
            
            //开始赋值
            for (YContactObject *object in contacts) {
                YContactPhoneObject *phontObject = [object.phoneObject firstObject];
                NSString *mobileNumStr = [phontObject.phoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
                if ([mobileNumStr isMobileNumber]){
                    DDLog(@"phoneNumber========================%@",mobileNumStr);
                    [mobileNumArr addObject:mobileNumStr];
                }
                
            }
            [weakSelf postSaveUserContacts:[mobileNumArr jsonStringEncoded]];
        }];
        [[HRContactsManager shareInstance] requestAuthorizationStatus];
    }else{
        [self postSaveUserContacts:[@[] jsonStringEncoded]];
    }
}


- (void)postSaveUserContacts:(NSString *)MobileList{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"UserLocalId"] = USERID;
    paramDict[@"MobileList"] = MobileList;
    paramDict[@"CreateTime"] = [self getCurrentTime];
    [self.locationViewModel postSaveUserContacts:paramDict isSeccess:^(BOOL isSeccess) {
        
    }];
}

- (NSString *)getCurrentTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    return [formatter stringFromDate:[NSDate date]];
}


-(void)calculateCacheMes{
    __weak typeof(self) weakSelf = self;
    
    // Count all cache size.
    // 计算缓存大小
    [[JPVideoPlayerCache sharedCache] calculateSizeWithCompletionBlock:^(NSUInteger fileCount, NSUInteger totalSize) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        NSString *cacheStr = [NSString stringWithFormat:@"总缓存大小: %0.2fMB, 总缓存文件数: %ld 个", (unsigned long)totalSize/1024./1024., (unsigned long)fileCount];
        
        
        cacheStr = [cacheStr stringByAppendingString:@", 你可以使用框架提供的方法, 清除所有缓存或指定的缓存, 具体请查看 `JPVideoPlayerCache`\n"];
        printf("%s", [cacheStr UTF8String]);
    }];
}

- (NSString *)getCaseData{
    NSInteger totalCount = [YYImageCache sharedCache].diskCache.totalCount;
    totalCount += [YYImageCache sharedCache].memoryCache.totalCount;

    totalCount += [[JPVideoPlayerCache sharedCache] getSize]/1024;
    
    
    totalCount += [[HRClearCacheTool getCacheSize] integerValue];
    
//    NSInteger totalCost = [YYImageCache sharedCache].memoryCache.totalCost;
    if (totalCount < 0){
        totalCount = 0;
    }
    if (!totalCount){
        return @"已清空";
    }
    return [NSString stringWithFormat:@"%.2fM",(float)totalCount/1024] ;

    
}


@end
